package org.sixtythousand.joker.handler;

import org.sixtythousand.joker.Request;
import org.sixtythousand.joker.Response;

/**
 * 基于HandlerWrapper实现handler的链式调用
 * HandlerWrapper里面的 handler对象相当于链表的 next 对象
 *
 * @author zhoulk
 * @date 2023/10/16 18:43
 * @desc
 */
public abstract class AbstractLinkedHandler extends AbstractHandlerWrapper implements LinkedHandler {


    @Override
    public void nextHandle(Request request, Response response) {
        handler.handle(request, response);
    }

    @Override
    public Handler nextHandler() {
        return handler;
    }

    @Override
    public void addHandlers(HandlerWrapper... handlers) {
        super.handlers = handlers;
        HandlerWrapper current = this;
        for (HandlerWrapper handler : handlers) {
            if (handler == current) {
                continue;
            }
            if (current.getHandler() == handler) {
                current = handler;
                continue;
            }

            if (current.getHandler() != handler) {
                current.setHandler(handler);
                current = handler;
                continue;
            }
        }

    }
}
